package com.smartrobot.smartrobot.Common;

import android.app.ActivityManager;
import android.content.Context;

import android.os.Handler;
import android.util.Log;
import android.view.View;
import com.loopj.android.http.*;
import com.readystatesoftware.viewbadger.BadgeView;

import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.util.HttpUtil;
import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

import java.security.MessageDigest;

import java.util.Date;
import java.util.Map;

/**
 * Created by ${yeluojun} on 2015/1/6.
 */
public class CommonFunc {


    //请求的公用函数
    public static void  c_http_post(boolean newClient,Map<String,String> param,final String url,final String dealClass,final String successMethod,final String failMethod,final Handler handler,final Context context,final Object ...obj){
        AsyncHttpClient client ;

        if(newClient){
            client =  new SyncHttpClient();
            PersistentCookieStore cookieStore = new PersistentCookieStore(context);
            client.setCookieStore(cookieStore);
        }else{
            if( HttpUtil.client==null){
                HttpUtil.init(context);
            }
            client = HttpUtil.client;
        }
        RequestParams params = new RequestParams();

        for (String key : param.keySet()) {
            String value = param.get(key);
            params.add(key, value);
        }

        client.post(url, params, new JsonHttpResponseHandler() {


            /**
             * statusCode 返回状态 heards响应头 响应服务器头 response 返回是json数据
             */
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {

                try {

                    System.out.println("成功：" + statusCode + " "
                            + response.toString());

                    if(obj!=null&&obj.length>0){
                        callMethodV2(context,dealClass, successMethod, response, handler, obj[0],Context.class,JSONObject.class, Handler.class,Object.class);
                    }else{
                        callMethod(context,dealClass, successMethod, response, handler,Context.class, JSONObject.class, Handler.class,Object.class);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {

                System.out.println("失败：" + statusCode + " ");

                callMethod(context,dealClass,failMethod,errorResponse,handler,Context.class,JSONObject.class,Handler.class,Object.class);

            }


            @Override
            public void   onFailure(int statusCode, Header[] headers, String repString , Throwable throwable){

                Log.e("==========hehheeh========", "onFailed");

                callMethod(context,dealClass,failMethod, null,handler,Context.class,JSONObject.class,Handler.class,Object.class);
            }

        });
    }



    //映射到函数
    public static void callMethod(Context context,String className, String methodName,JSONObject response,final Handler handler,Class...parameterType){
        try{

            Class c = Class.forName(className);

            Method m = c.getMethod(methodName,parameterType);

            Object o = m.invoke(c.newInstance(),context,response,handler,null);

        }catch (Exception e){
            System.out.println("失败：" + "映射到类名：" + className+"失败");
            System.out.println("失败原因："+e.getMessage());
            e.printStackTrace();// 打印失败
            LogToSd.error(e.getLocalizedMessage());
            LogToSd.error(e.getMessage());
        }
    }



    //映射到函数v2
    public static void callMethodV2(Context context,String className, String methodName,JSONObject response,final Handler handler,final Object object,Class...parameterType){
        try{

            Class c = Class.forName(className);

            Method m = c.getMethod(methodName,parameterType);

            Object o = m.invoke(c.newInstance(),context,response,handler,object);

        }catch (Exception e){
            System.out.println("失败：" + "映射到类名：" + className+"失败");
            System.out.println("失败原因："+e.getMessage());
            e.printStackTrace();// 打印失败
            LogToSd.error(e.getLocalizedMessage());
            LogToSd.error(e.getMessage());
        }
    }

    //转化为md5
    public static String stringToMD5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10)
                    hex.append("0");
                hex.append(Integer.toHexString(b & 0xFF));
            }

            return hex.toString();
        }catch (Exception e){
            return "";
        }

    }


    public static byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];

        for(int i = 0; i < len; i += 2) {
            data[i / 2] = (byte)((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }

        return data;
    }


    public static Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;

        try {
            ObjectInputStream e = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableCookie)e.readObject()).getCookie();
        } catch (IOException var6) {
            Log.d("PersistentCookieStore", "IOException in decodeCookie", var6);
        } catch (ClassNotFoundException var7) {
            Log.d("PersistentCookieStore", "ClassNotFoundException in decodeCookie", var7);
        }

        return cookie;
    }


    //获取时间
    public static String getTime(){
            Date date = new Date();
            return date.getTime()+"";
    }


    //获取当前活动的activity
    public static  String getRunningActivityName(Context context){
        ActivityManager activityManager=(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }




    //显示BadgeView
    public static BadgeView showBadgeView(BadgeView badge,Context context,View target,int num){



        if(context!=null&&target!=null||badge!=null){

            badge.setText("new");
            badge.show();
            return  badge;
        }
        return null;
    }

    //隐藏badgeView
    public static void hideBadgeView(BadgeView badgeView){
        if(badgeView!=null){
            badgeView.hide();
        }
    }


}
